package com.walter.gateway.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;

/**
 * @author Walter
 * @date 2025/2/6 下午5:16
 **/
@Slf4j
public class IpAddrUtil {
    private static final String UNKNOWN_IP = "0.0.0.0";

    /**
     *  获取本地IP地址
     * @return IP地址
     */
    public static String getLocalIpAddress(){
        try {
            InetAddress localHost = InetAddress.getLocalHost();
            String ipAddress = localHost.getHostAddress();
            log.info("本地IP地址 : {}", ipAddress);
            return ipAddress;
        } catch (UnknownHostException e) {
            log.error("无法获取本地IP地址: {}", e.getMessage());
            return UNKNOWN_IP;
        }
    }
    /**
     * 获取请求客户端的IP地址
     * @param request 请求对象
     * @return  IP地址
     */
    public static String getClientIpAddress(ServerHttpRequest request) {
        HttpHeaders headers = request.getHeaders();
        String ipAddress = headers.getFirst("X-Forwarded-For"); // 优先从 X-Forwarded-For 获取

        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = headers.getFirst("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = headers.getFirst("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = headers.getFirst("HTTP_CLIENT_IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = headers.getFirst("HTTP_X_FORWARDED_FOR");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            InetSocketAddress remoteAddress = request.getRemoteAddress();
            if (remoteAddress != null) {
                ipAddress = remoteAddress.getAddress().getHostAddress();
            }
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = UNKNOWN_IP; // 默认值
        }
        return ipAddress;
    }
}
